﻿<template>
  <div class="problems-container">
    <!-- 页面头部 -->
    <div class="problems-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="main-title">题目管理</h1>
          <p class="subtitle">管理系统中的所有题目，包括创建、编辑和删除</p>
        </div>
        <div class="stats-section">
          <div class="stat-item">
            <div class="stat-value">{{ total }}</div>
            <div class="stat-label">题目总数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value active">{{ total }}</div>
            <div class="stat-label">已发布</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="toolbar-left">
        <el-input
          v-model="searchProblems.title"
          placeholder="搜索题目标题..."
          prefix-icon="Search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
        <el-select
          v-model="searchProblems.difficulty"
          placeholder="难度筛选"
          clearable
          class="filter-select"
          @change="handleSearch"
        >
          <el-option label="简单" value="简单" />
          <el-option label="中等" value="中等" />
          <el-option label="困难" value="困难" />
        </el-select>
      </div>
      <div class="toolbar-right">
        <el-button type="primary" @click="handleAdd" class="add-button">
          <el-icon><Plus /></el-icon>
          新增题目
        </el-button>
      </div>
    </div>

    <!-- 题目列表 -->
    <div class="problems-content" v-loading="loading">
      <div class="list-view">
        <el-table
          :data="problemList"
          class="problems-table"
          @selection-change="handleSelectionChange"
          ref="problemTable"
          row-class-name="problem-row"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="#" width="80" align="center" />
          <el-table-column prop="title" label="题目" min-width="300">
            <template #default="{ row }">
              <div class="problem-title-cell">
                <span class="title-text">{{ row.title }}</span>
                <div class="description-text" v-if="row.description">
                  {{ row.description.substring(0, 50) }}{{ row.description.length > 50 ? "..." : "" }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="难度" width="120" align="center">
            <template #default="{ row }">
              <div class="status-pill" :class="getDifficultyClass(row.difficulty)">
                {{ row.difficulty }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分类" min-width="160" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.category" size="small" class="category-tag" effect="plain">
                {{ row.category }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="时间限制" prop="timeLimit" width="120" align="center" show-overflow-tooltip>
            <template #default="{ row }"> {{ row.timeLimit }} ms </template>
          </el-table-column>
          <el-table-column label="内存限制" prop="memoryLimit" width="120" align="center" show-overflow-tooltip>
            <template #default="{ row }"> {{ row.memoryLimit }} MB </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createdAt" width="180" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button type="primary" link @click="handleEdit(row)" class="operation-button"> 修改 </el-button>
                <el-button type="danger" link @click="handleDelete(row)" class="operation-button"> 删除 </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加题目组件 -->
    <ProblemEditForm v-model:visible="addDialogVisible" mode="add" @success="handleFormSuccess" />

    <!-- 编辑题目组件 -->
    <ProblemEditForm
      v-model:visible="updateDialogVisible"
      mode="edit"
      :problem-data="currentProblem"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script>
export default {
  name: "ProblemManagement",
};
</script>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useProblemsStore } from "@/stores/modules/problem";
import ProblemEditForm from "./components/problemEditForm.vue";
import { usePagination } from "@/composables/core/usePagination";
import dayjs from "dayjs";

// 使用store获取全局管理的状态
const problemsStore = useProblemsStore();

// 搜索表单
const searchProblems = reactive({
  title: "",
  difficulty: "",
});

// 状态变量
const addDialogVisible = ref(false);
const updateDialogVisible = ref(false);
const selectedProblems = ref([]);
const problemTable = ref(null);
const currentProblem = ref(null);

// 题目列表和加载状态
const loading = computed(() => problemsStore.loading);
const problemList = computed(() => problemsStore.problems);

// 初始化分页
const pagination = usePagination(1, 10);
const currentPage = pagination.pageNum;
const pageSize = pagination.pageSize;
const total = pagination.total;
const setTotal = pagination.setTotal;
const resetPagination = pagination.reset;

// 分页处理函数
const handleSizeChange = newSize => {
  pageSize.value = newSize;
  currentPage.value = 1;
  loadProblemList();
};

const handleCurrentChange = newPage => {
  currentPage.value = newPage;
  loadProblemList();
};

// 选择处理
const handleSelectionChange = rows => {
  selectedProblems.value = rows;
};

// 加载题目列表
const loadProblemList = async () => {
  try {
    // 构建查询参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchProblems.title,
      difficulty: searchProblems.difficulty,
      isAdmin: true, // 管理员接口
    };

    await problemsStore.getProblemList(params);

    // 从store获取数据
    setTotal(problemsStore.total);
  } catch (error) {
    ElMessage.error("获取题目列表失败");
    setTotal(0);
  }
};

// 搜索处理
const handleSearch = () => {
  // 重置页码到第一页
  currentPage.value = 1;
  // 重新加载数据
  loadProblemList();
};

const resetSearch = () => {
  Object.assign(searchProblems, {
    title: "",
    difficulty: "",
  });
  // 重置页码到第一页
  currentPage.value = 1;
  loadProblemList();
};

/**
 * 根据难度获取对应的样式类名
 * @param {string} difficulty - 难度级别
 * @returns {string} CSS 类名
 */
const getDifficultyClass = difficulty => {
  if (difficulty === "简单") return "status-easy";
  if (difficulty === "中等") return "status-medium";
  if (difficulty === "困难") return "status-hard";
  return "";
};

// 格式化日期
const formatDate = dateStr => {
  if (!dateStr) return "未知";
  return dayjs(dateStr).format("YYYY-MM-DD HH:mm");
};

// 新增题目
const handleAdd = () => {
  currentProblem.value = null;
  addDialogVisible.value = true;
};

/**
 * 编辑题目
 * @param {Object} row - 题目数据
 */
const handleEdit = async row => {
  try {
    const response = await problemsStore.getProblemById(row.id);

    if (response && response.code === 200 && response.data) {
      currentProblem.value = response.data;
      updateDialogVisible.value = true;
    } else {
      ElMessage.error(response?.message || "获取题目详情失败");
    }
  } catch (error) {
    ElMessage.error("获取题目详情失败");
  }
};

// 表单操作成功的回调
const handleFormSuccess = () => {
  // 重置分页并重新加载数据
  resetPagination();
  loadProblemList();
};

/**
 * 删除题目
 * @param {Object} row - 题目数据
 */
const handleDelete = async row => {
  try {
    await ElMessageBox.confirm(`确定要删除题目 "${row.title}" 吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const res = await problemsStore.deleteProblem(row.id);

    if (res && res.code === 200) {
      ElMessage.success(res.message);
      // 刷新列表
      loadProblemList();
    } else {
      ElMessage.error(res?.message);
    }
  } catch (error) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      ElMessage.error("删除操作异常");
    }
  }
};

// 组件挂载时加载题目列表
onMounted(() => {
  loadProblemList();
});
</script>

<style scoped lang="scss">
@use "@/styles/base/variables" as *;
@use "@/styles/base/mixins" as *;
@use "@/styles/pages/common" as *;

/* 使用统一的管理页面样式，只保留页面特定的样式 */
.problems-container {
  @extend .admin-container;
}

.problems-header {
  @extend .admin-header;
}

.problems-content {
  @extend .admin-content;

  .problems-table {
    @extend .admin-table;
  }
}

.pagination-wrapper {
  @extend .admin-pagination;
}

/* 页面特定样式 */
.problem-title-cell {
  @extend .table-title-cell;
}

.add-button {
  display: flex;
  align-items: center;
  gap: $spacing-sm;
}
</style>
